package zhou.chs.p4_6;

import android.Manifest;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;

public class MyService extends Service implements LocationListener {
    static final int MIN_TIME = 5000;       // 位置更新条件：5000 毫秒
    static final float MIN_DIST = 5;        // 位置更新条件：5 米
    LocationManager mManager;                   // 定位管理器
    private Handler mHandler;   //消息线程
    private Socket mSocket;     //TCP_Client Socket
    private StartThread st;     //TCP客户端线程
    private ConnectedThread rt; //TCP数据交换线程
    private String strRxd = "";        //接收端文本
    private byte rbuf[] = new byte[512];		//接收数据
    private int len;    //接收数据长度
    boolean running = false;
    int tn;   //1s计数
    int wn;   //网络通信计数，收到checked清零，每秒计数，超过5分钟，wn>300时网络状态值清零，重新登录
    int sta=1;   //状态值： 1-有网络  2-连接到贝壳网络  3-设备已登录
    double mlatitude;  //纬度值
    double mlongitude;  //经度值
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override   // 服务初始化
    public void onCreate() {
        super.onCreate();
        mHandler = new MyHandler();//实例化Handler，用于进程间的通信
        Timer mTimer = new Timer();         //新建Timer
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                tn++;                   //每秒加1
                wn++;
                Message msg2 = mHandler.obtainMessage();   //创建消息
                msg2.what = 2;                      //变量what赋值
                mHandler.sendMessage(msg2);     //发送消息
            }
        }, 1000, 1000);     //延时1000ms，然后每隔1000ms发送消息
        mManager = (LocationManager) getSystemService(LOCATION_SERVICE);     // 获取系统定位管理器
        // 开始监听位置事件
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mManager.requestLocationUpdates(mManager.GPS_PROVIDER, MIN_TIME, MIN_DIST, this);
    }
    @Override   //
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
    @Override   //服务停止
    public void onDestroy() {
        super.onDestroy();
        mManager.removeUpdates(this);   // 停止监听位置事件
    }

    // 位置变化监听响应
    @Override
    public void onLocationChanged(Location location) {
        mlatitude = location.getLatitude();
        mlongitude = location.getLongitude();
        String strtxv = String.format("\n纬度:%.6f\n经度:%.6f",
                mlatitude,         // 纬度
                mlongitude);       // 经度
    }
    @Override       // GPS停用
    public void onProviderDisabled(String provider) {  }
    @Override       // GPS启用
    public void onProviderEnabled(String provider) {  }
    @Override       // 定位提供者状态变化
    public void onStatusChanged(String provider, int status, Bundle extras) { }
    //建立socket连接的线程
    private class StartThread extends Thread{
        @Override
        public void run() {
            try {
                mSocket = new Socket("121.42.180.30", 8181);//连接贝壳物联服务器
                //启动接收数据的线程
                rt = new ConnectedThread(mSocket);
                rt.start();
                running = true;
                if(mSocket.isConnected()){           //成功连接获取socket对象则发送成功消息
                    Message msg0 = mHandler.obtainMessage();
                    msg0.what=0;
                    mHandler.sendMessage(msg0);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //数据输入输出线程
    private class ConnectedThread extends Thread {
        private final Socket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        public ConnectedThread(Socket socket) {   //socket连接
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            try {
                tmpIn = mmSocket.getInputStream();      //数据通道创建
                tmpOut = mmSocket.getOutputStream();
                Message msg0 = mHandler.obtainMessage();
                msg0.what = 0;
                mHandler.sendMessage(msg0);
            } catch (IOException e) { }
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }
        public final void run() {
            while (running) {
                int byt;
                try {
                    byt = mmInStream.read(rbuf);     // 监听接收到的数据
                    if(byt>0){
                        Message msg1 = mHandler.obtainMessage();
                        msg1.what = 1;
                        msg1.obj=byt;
                        mHandler.sendMessage(msg1); // 通知主线程接收到数据
                        try{
                            sleep(200);
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                } catch (NullPointerException e) {
                    running = false;
                    Message msg2 = mHandler.obtainMessage();
                    msg2.what = 2;
                    mHandler.sendMessage(msg2);
                    e.printStackTrace();
                    break;
                } catch (IOException e) {
                    break;
                }
            }
        }
        public void write(byte[] bytes) {       //发送字节数据
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) { }
        }
        public void cancel() {      //关闭连接
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }
    //在主线程处理Handler传回来的message
    class  MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0: //已连接网络
                    break;
                case 1: //收到网络数据
                    len=Integer.parseInt(msg.obj.toString());
                    strRxd="";
                    for(int i=0;i<len;i++){
                        strRxd = strRxd + String.format("%c",rbuf[i]);
                    }
                    // 网络数据解析
                    int n = strRxd.indexOf("WELCOME TO BIGIOT");
                    if(n>0) sta=2;  //收到"WELCOME TO BIGIOT"，表示已连接贝壳物联网
                    n = strRxd.indexOf("checkinok");
                    if(n>0) {   //收到"checkinok"，表示设备已登录
                        sta=3;
                        tn=30;
                    }
                    n = strRxd.indexOf("checked");
                    if(n>0) wn=0;   //收到"checked"，表示设备在线
                    break;
                case 2:     //定时1s
                    if(wn>300){
                        wn=0;
                        sta=1;
                    }
                    switch (sta) {
                        case 1:     // 有网络
                            st = new StartThread();
                            st.start(); //连接贝壳物联
                            break;
                        case 2:     // 已连接贝壳物联
                            String s = "{\"M\":\"checkin\",\"ID\":\"2334\",\"K\":\"5bd854981\"}\n";
                            //tvTxd.setText(s);
                            try {       //设备登录
                                rt.write(s.getBytes("utf-8"));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            break;
                        case 3:     // 设备已登录
                            if(tn==60){
                                s = "{\"M\":\"status\"}\n";
                                //tvTxd.setText(s);
                                strRxd="";
                                //tvRxd.setText(strRxd);
                                try {       //每隔1s发查询状态
                                    rt.write(s.getBytes("utf-8"));
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            if(tn>=120){
                                tn=0;
                                s = "{\"M\":\"update\",\"ID\":\"2334\",\"V\":{\"2244\":\"" + String.format("%.6f", (float)mlongitude) + ","+ String.format("%.6f", (float)mlatitude) + "\"}}\n";

                                try {       //每隔1s发定位数据
                                    rt.write(s.getBytes("utf-8"));
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            break;
                    }
                    break;
            }
        }
    }
}
